package org.sucri.servlet.handler;

import org.sucri.floxs.servlet.User;
import org.sucri.floxs.servlet.RequestHandler;
import org.sucri.floxs.Tools;
import org.sucri.dao.UsersEntity;
import org.apache.commons.collections15.map.MultiKeyMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.IOException;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Wen Yu
 * Date: Aug 25, 2007
 * Time: 1:39:23 PM
 * To change this template use File | Settings | File Templates.
 */
public class LoginHandler extends RequestHandler$
{
  public LoginHandler(String page)
  {
    super(page, "login");
  }
  public LoginHandler(MultiKeyMap<String, RequestHandler> s)
  {
    super(null, "login", s);
  }
  public boolean processRequest(EntityManagerFactory emf,
                                User                 user,
                                HttpServletRequest   req,
                                HttpServletResponse  res)
      throws ServletException, IOException
  {
    String username = req.getParameter("username");
    String password = req.getParameter("userpass");
    //action=login&username=Test&password=Test
/*    try
    {
      Class.forName("org.sucri.dao.UsersEntity");
      Class.forName("org.sucri.dao.PetsEntity");
      Class.forName("org.sucri.dao.ItemsEntity");
    }
    catch (ClassNotFoundException e)
    {
      e.printStackTrace();
    }
*/
    EntityManager em =  emf.createEntityManager();

    Query query = em.createQuery("select e from UsersEntity e where e.uname = '" + username + "' and e.password = '" + password + "'");
    List<UsersEntity> users = query.getResultList();

    em.close();
    
    if (Tools.good(users)) res.getOutputStream().println("{success:true}");
    else                   res.getOutputStream().println("{errors: true}");

    return true;
  }
  
}
